#include "game.h"

Game::Game(  )
{

}

Game::~Game(  )
{

}

void Game::init(  )
{
	if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
		std::cout << "Error initialising SDL" << std::endl;
		return;
	}

	// Request an opengl 3.3 context
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
	SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

	// Enable multi-sampling
	//SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
	//SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 4 );
	
	wnd = SDL_CreateWindow( "ANNTTT", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
	
	if ( !wnd )
	{
		std::cout << "Error creating window" << std::endl;
		return;
	}

	glc = SDL_GL_CreateContext( wnd );
	
	// Disable v-sync
	SDL_GL_SetSwapInterval( 0 );

	// Enable experimental features for Opengl 3.3+ core
	glewExperimental = true;
	GLenum glewerr = glewInit(  );
	if ( glewerr != GLEW_OK )
	{
		std::cout << "Error initialising GLEW" << std::endl;
		std::cout << glewGetErrorString( glewerr ) << std::endl;
		return;
	}
	
	glEnable( GL_DEPTH_TEST );
	glEnable( GL_CULL_FACE );

	glClearColor( 0.5f, 0.5f, 0.5f, 1.0f );

	memset( keyPressed, false, 512 );
}

void Game::render(  ) const
{
	glClear( GL_COLOR_BUFFER_BIT );



	SDL_GL_SwapWindow( wnd );
}

void Game::run(  )
{
	running = true;

	while ( running )
	{
		update(  );
		render(  );
	}
}

void Game::update(  )
{
	const int EVENT_BUFFER_SIZE = 256;

	SDL_Event event[ EVENT_BUFFER_SIZE ];    //The SDL event that we will poll to get events.
	
	// Got to pump the events before we can peep
	SDL_PumpEvents(  );

	int numEvents = SDL_PeepEvents( event, EVENT_BUFFER_SIZE, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT );

	for ( int i = 0; i < numEvents; ++i )
	{
		switch ( event[ i ].type )
		{
		case SDL_QUIT:
			running = false;
			break;
		// Keyboard
		case SDL_KEYDOWN:
		case SDL_KEYUP:
		{
			SDL_KeyboardEvent kevent = event[ i ].key;

			// SDL_KEYDOWN = 768, SDL_KEYUP = 769
			// SDL_KEYDOWN & 1 returns 0
			// SDL_KEYUP & 1 return 1
			keyPressed[ kevent.keysym.scancode ] = !( kevent.type & 1 );
			break;
		}
		default:
			//std::cout << event[ i ].type << std::endl;
			//std::cout << event.type << std::endl;
			break;
		};
	}

	if ( keyPressed[ SDL_SCANCODE_ESCAPE ] )
		running = false;

	if ( keyPressed[ SDL_SCANCODE_A ] )
		std::cout << "A" << std::endl;
}